import { api, LightningElement, track } from 'lwc';
import { data1, data2, freezeColumns, columns } from './data';

export default class TestLwcIfSingle extends LightningElement {

    isLoading = false;

    @track dataRows = [];
    // dataRows = [];

    columns = columns;

    freezeColumns = freezeColumns;


    reloadData() {

        // 改造前：
        this.isLoading = true;
        if(Math.ceil(Math.random() * 10) % 2 == 0) {
            this.dataRows = JSON.parse(JSON.stringify(data1));
        } else {
            this.dataRows = JSON.parse(JSON.stringify(data2));
        }
        this.isLoading = false;

        // 改造后：
        // 一定要在更新数据前先清空旧数据，然后在异步线程中更新数据，重新渲染DOM
        // 否则DOM状态不一致，会报错：Uncaught (in promise) TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.
        // this.isLoading = true;
        // this.dataRows.splice(0);
        // setTimeout(() => {
        //     if(Math.ceil(Math.random() * 10) % 2 == 0) {
        //         this.dataRows = JSON.parse(JSON.stringify(data1));
        //     } else {
        //         this.dataRows = JSON.parse(JSON.stringify(data2));
        //     }
        //     this.isLoading = false;
        // }, 0);
    }

    toggleRowExpand(event) {
        // 1. change button icon
        // 2. hide/show children row
        let target = event.target;
        let iconName = target.iconName;
        let idx = target.dataset.idx;
        console.log('idx: ' + idx +', iconName: ' + iconName);
        if(iconName === 'utility:chevrondown') {
            // Collapse children row
            target.iconName = 'utility:chevronright';
            this.dataRows[idx].expanded = false;
        } else {
            // Expand children row
            target.iconName = 'utility:chevrondown';
            this.dataRows[idx].expanded = true;
        }
    }

}